# file: liuyao/core/validator.py

from typing import Dict
from core.validation.exceptions import InvalidGuaDictError


def validate_gua_dict(gua_dict: Dict) -> None:
    """
    校验卦象字典的数据合法性
    验证gua_dict 的 m,dg,d,gua 都是数字，非空，
    m，d in 0-11，
    dg in 0-9,
    gua in 0-63,
    biangua is None.或者 in 0-63

    :param gua_dict: 待校验的卦象字典
    :raises InvalidGuaDictError: 如果校验失败
    """
    required_keys = ['m', 'dg', 'd', 'gua']
    for key in required_keys:
        if key not in gua_dict:
            raise InvalidGuaDictError(f"缺少必要字段: {key}")

    try:
        m = int(gua_dict['m'])
        dg = int(gua_dict['dg'])
        d = int(gua_dict['d'])
        gua = int(gua_dict['gua'])
    except (TypeError, ValueError):
        raise InvalidGuaDictError("m, dg, d, gua 必须是整数")

    if not (0 <= m <= 11):
        raise InvalidGuaDictError("m 必须在 0~11 范围内")
    if not (0 <= dg <= 9):
        raise InvalidGuaDictError("dg 必须在 0~9 范围内")
    if not (0 <= d <= 11):
        raise InvalidGuaDictError("d 必须在 0~11 范围内")
    if not (0 <= gua <= 63):
        raise InvalidGuaDictError("gua 必须在 0~63 范围内")

    biangua = gua_dict.get('biangua')
    if biangua is not None:
        try:
            biangua = int(biangua)
            if not (0 <= biangua <= 63):
                raise InvalidGuaDictError("biangua 必须在 0~63 范围内或为 None")
        except (TypeError, ValueError):
            raise InvalidGuaDictError("biangua 必须是整数或 None")
